<?php defined('SYSPATH') or die('No direct script access.');

// Категории
class Controller_Admin_Categories extends Controller_Admin_Base
{
	public function action_index()
	{
        $message = null;
        
		// Доавление категории
        if ($this->request->method() == HTTP_Request::POST)
        {            
            $action = $this->request->post('action');
            
            if($action == 'add_category')
            {
                $title = $this->request->post('title') ? trim($this->request->post('title')) : null;
                $url   = $this->request->post('url') ? trim($this->request->post('url')) : null;

                if($title && $url)
                {
                    $category_id = $this->category_model->add_category($title, $url);
                    $message = 'Категория добавлена успешно!';
                }
            }
            else if($action == 'edit_category')
            {
                $title       = $this->request->post('title') ? trim($this->request->post('title')) : null;
                $url         = $this->request->post('url') ? trim($this->request->post('url')) : null;
                $category_id = $this->request->post('category_id') ? (int)$this->request->post('category_id'): null;

                if($title && $url && $category_id)
                {
                    $this->category_model->update_category($title, $url, $category_id);
                    $message = 'Успешно отредактировали!'; 
                }
            }
            else if($action == 'delete_categories')
            {                
                $categories = $this->request->post('categories') ? $this->request->post('categories') : null;
                
                if($categories)
                {
                    foreach($categories as $category_id)
                    {
                        $this->category_model->delete_category($category_id);
                    }
                    
                    $message = 'Удалили'; 
                }
            }
        }
        
        $categories = $this->category_model->get_categories();
        
        $title = 'Категории';
        $content = new View('admin/categories/categories_tpl');
        $content->categories = $categories;
        $content->message    = $message;
        
        
        $menu = array(
            'menu'    => 3,
            'submenu' => 31
        );
        
        $this->print_template($title, $content, $menu);
	}
    
    public function action_delete()
    {
        $category_id = $this->request->param('id');
        
        if($category_id)
            $this->category_model->delete_category($category_id);
            
        Request::current()->redirect($this->request->referrer());
    }
} // End Ajax_Categories
